﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using D2D2.Server.Networking;
using D2D2.SharedInterfaces.Networking;

namespace D2D2.Server.Core
{
    public class PlayerManagerServer
    {
        private List<PlayerObject> _players = new List<PlayerObject>();
        private long _playerCounter;
        private ServerManager _serverManager;

        public PlayerManagerServer(ServerManager serverManager)
        {
            _serverManager = serverManager;
        }

        public PlayerObject AddPlayer()
        {
            PlayerObject playerObject = new PlayerObject();

            long id = Interlocked.Increment(ref _playerCounter);

            playerObject.Id = id;
            playerObject.Strength = 10;
            playerObject.Dexterity = 10;
            playerObject.Energy = 10;
            playerObject.Intelligence = 10;
            playerObject.Level = 1;
            playerObject.Money = 0;
            playerObject.Alive = true;
            playerObject.LiveHitTime = 0.15f;
            playerObject.ActionHitTime = 0.15f;

            Calculate(playerObject);

            playerObject.CurrentLive = playerObject.TotalLive;
            playerObject.CurrentAction = playerObject.TotalAction;

            _players.Add(playerObject);

            return playerObject;
        }

        public PlayerObject GetPlayer(long id)
        {
            return _players.Find(p => p.Id == id);
        }

        private void Calculate(PlayerObject playerObject)
        {
            playerObject.TotalLive = playerObject.Energy*5 + playerObject.Strength*2;
            playerObject.TotalAction = playerObject.Energy*2 + playerObject.Dexterity;
            playerObject.MinDamage = playerObject.Level*2 + (playerObject.Strength/100)*playerObject.Level*2;
            playerObject.MaxDamage = playerObject.Level*3 + (playerObject.Strength/100)*playerObject.Level*3;
            playerObject.LiveRegen = playerObject.Level;
            playerObject.ActionRegen = playerObject.Level*8;
        }

        public void Update(float elapsed)
        {

            foreach (PlayerObject player in _players)
            {
                player.CalculateLive(elapsed);
                player.CalculateAction(elapsed);
                _serverManager.SendMessage(player);
            }
        }
    }
}
